package logs

import (
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
	"io"
	"os"
	"runtime"
	"strings"
)

//gin使用rlog记录日志
//	gin.DefaultWriter = rlog.GetOutput() // gin框架自己记录的日志也会输出

var logger *logrus.Entry

func init() {
	//UseRollingFileAppender("shop.log", "text", LogLevelAll, 500, 3, 30)
	UseConsoleAppender(logrus.DebugLevel, "json")
	//UseRollingFileAppender("logrus.log", "text", logrus.DebugLevel, 500, 3, 30)
	//gin.DefaultWriter = logger.Logger.Out
}

func Logger() *logrus.Entry {
	return logger
}

// @title    UseConsoleAppender
// @description   设置日志输出到标准输出，建议程序启动时设置，程序默认输出到标准输出
// @param     level   日志级别
// @parma     formatter  日志格式， text or json
func UseConsoleAppender(level logrus.Level, formatter string) {
	rootLogger := logrus.New()

	setFormatter(rootLogger, formatter)
	rootLogger.SetLevel(level)
	rootLogger.SetOutput(os.Stderr)

	logger = logrus.NewEntry(rootLogger)
}

func SetLogConfig(level logrus.Level, formatter string) {
	if logger != nil {
		setFormatter(logger.Logger, formatter)
		logger.Logger.SetLevel(level)
	}
}

func setFormatter(logger *logrus.Logger, formatter string) {
	if formatter == "json" {
		customFormatter := new(logrus.JSONFormatter)
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"
		logger.SetFormatter(customFormatter)
	} else {
		customFormatter := new(logrus.TextFormatter)
		customFormatter.TimestampFormat = "2006-01-02 15:04:05"
		logger.SetFormatter(customFormatter)
	}
}

// @title    UseRollingFileAppender
// @description   设置日志输出到可切割的文件，建议程序启动时设置
// @param     filename     日志文件路径
// @parma     formatter    日志格式， text or json
// @param     level        日志级别
// @param     maxSize      日志文件最大大小，单位MB
// @param     maxBackup    最多备份日志的数量
// @param     maxAge       备份日志保存天数

func UseRollingFileAppender(filename string, formatter string, level logrus.Level, maxSize, maxBackup, maxAge int) {
	l := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    maxSize, // megabytes
		MaxBackups: maxBackup,
		MaxAge:     maxAge, //days
		Compress:   false,  // disabled by default
	}

	rootLogger := logrus.New()

	setFormatter(rootLogger, formatter)
	rootLogger.SetLevel(level)
	rootLogger.SetOutput(l)

	logger = logrus.NewEntry(rootLogger)
}

func GetLoggerWithPackageName() *logrus.Entry {
	pc, _, _, ok := runtime.Caller(1)

	if ok {
		f := runtime.FuncForPC(pc)
		funcName := f.Name()

		pos := strings.LastIndex(funcName, ".")
		if pos > 0 {
			return logger.WithField("package", funcName[:pos])
		}

		return logger
	}

	return logger
}

func GetOutput() io.Writer {
	return logger.Logger.Out
}
